/**
 * 自动化表单验证
 * Created on 2017/2/14
 * rules: [
 *      unique,
 *      timestamp, //日期时间格式（如2011-08-15 13:40:00）
 *      shortTimestamp, //日期时间格式（如2011-08-15 13:40）
 *      yearMonth, //年月格式（如201201）
 *      startWith, //以{0}开头字符串
 *      dateLT, //输入的日期数据必须小于结束日期
 *      dateGT, //输入的日期数据必须大于开始日期
 *      idCardNo, //有效的身份证件号
 *      phone, //有效的电话号码：数字或'-'
 *      mobile, //有效的手机号码
 *      zipCode, //6位数字邮政编码
 *      numberEndWithPointFive, //以.0或.5作为小数结尾
 *      equalToByName, //前后相等数据
 *      idCardNoSex, //身份证号与性别是否匹配
 *      requiredByName, //依赖关系必须填写
 *      remoteCallback, //远程数据校验
 *      regex, //自定义正则表达式数据校验
 *      custom, //元素属性data-rule-custom校验
 *      email, //邮箱
 *      checkFloatPercent, //百分数(允许两位小数)
 *      checkNum, //正确的数字
 *      checkCount, //正确的数字，只能有3位小数
 *      checkMoney，//验证金额，只能有2位小数
 *      checkUser, //用户名必须为字母+数字
 *      checkPwd, //密码6-10位，必须为字母+数字+特殊字符
 * ]
 */
 var FormValidation = function () {

  // private functions & variables

  // public functions
  return {

      init: function () {
          jQuery.validator.addMethod("onlyletter", function (value, element) {
              var tel = /^[A-Za-z]*$/;
              return this.optional(element) || (tel.test(value));
          }, "仅支持英文字符");

          // 只能输入中文
          $.validator.addMethod("onlyCN", function (value, element) {
              var tel = /^[\u4e00-\u9fa5]*$/;
              return this.optional(element) || (tel.test(value));
          }, "仅支持中文字符");

          /**
           * 校验输入值需要满足时间格式
           */
          jQuery.validator.addMethod("timestamp", function (value, element) {
              if (value == "") {
                  return this.optional(element);
              }
              var regex = /^(?:[0-9]{4})-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/;
              if (!regex.test(value)) {
                  return false;
              }
              return true;
          }, "请输入合法的日期时间格式（如2011-08-15 13:40:00）");

          /**
           * 校验输入值需要满足短时间格式，精确到分的时间格式
           */
          jQuery.validator.addMethod("shortTimestamp", function (value, element) {
              if (value == "") {
                  return this.optional(element);
              }
              var regex = /^(?:[0-9]{4})-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/;
              if (!regex.test(value)) {
                  return false;
              }
              return true;
          }, "请输入合法的日期时间格式（如2011-08-15 13:40）");

          /**
           * 校验输入值满足年月格式
           */
          jQuery.validator.addMethod("yearMonth", function (value, element) {
              if (value == "") {
                  return this.optional(element);
              }
              var regex = /^(?:[0-9]{4})(?:(?:0[1-9])|(?:1[0-2]))$/;
              if (!regex.test(value)) {
                  return false;
              }
              return true;
          }, "请输入合法的年月格式（如201201）");

          jQuery.validator.addMethod("startWith", function (value, element, param) {
              if (this.optional(element)) {
                  return true;
              }
              if (param.length > value.length) {
                  return false;
              }
              if (value.substr(0, param.length) == param) {
                  return true;
              } else {
                  return false;
              }
          }, "请输入以{0}开头字符串");

          /**
           * 校验当前输入日期值应该小于目标元素日期值， 如果目标元素没有输入值，校验认为通过 主要用于两个日期区间段输入校验彼此日期先后合理性
           */
          jQuery.validator.addMethod("dateLT", function (value, element, param) {
              if (value == "") {
                  return this.optional(element);
              }

              var $param = $(param);
              if ($param.size() == 0) {
                  $param = $(element).closest("form").find("[name='" + param + "']");
              }
              var endDate = $param.val();
              if (endDate == "") {
                  return true;
              }

              var startDate = eval("new Date(" + value.replace(/[\-\s:]/g, ",") + ")");
              endDate = eval("new Date(" + endDate.replace(/[\-\s:]/g, ",") + ")");

              if (startDate > endDate) {
                  return false;
              } else {

                  return true;
              }
          }, "输入的日期数据必须小于结束日期");

          /**
           * 校验当前输入日期值应该大于目标元素日期值， 如果目标元素没有输入值，校验认为通过 主要用于两个日期区间段输入校验彼此日期先后合理性
           */
          jQuery.validator.addMethod("dateGT", function (value, element, param) {
              if (value == "") {
                  return this.optional(element);
              }

              var $param = $(param);
              if ($param.size() == 0) {
                  $param = $(element).closest("form").find("[name='" + param + "']");
              }
              var startDate = $param.val();
              if (startDate == "") {
                  return true;
              }

              var endDate = eval("new Date(" + value.replace(/[\-\s:]/g, ",") + ")");
              startDate = eval("new Date(" + startDate.replace(/[\-\s:]/g, ",") + ")");

              if (startDate > endDate) {

                  return false;
              } else {

                  return true;
              }
          }, "输入的日期数据必须大于开始日期");

          var idCardNoUtil = {

              /* 省,直辖市代码表 */
              provinceAndCitys: {
                  11: "北京",
                  12: "天津",
                  13: "河北",
                  14: "山西",
                  15: "内蒙古",
                  21: "辽宁",
                  22: "吉林",
                  23: "黑龙江",
                  31: "上海",
                  32: "江苏",
                  33: "浙江",
                  34: "安徽",
                  35: "福建",
                  36: "江西",
                  37: "山东",
                  41: "河南",
                  42: "湖北",
                  43: "湖南",
                  44: "广东",
                  45: "广西",
                  46: "海南",
                  50: "重庆",
                  51: "四川",
                  52: "贵州",
                  53: "云南",
                  54: "西藏",
                  61: "陕西",
                  62: "甘肃",
                  63: "青海",
                  64: "宁夏",
                  65: "新疆",
                  71: "台湾",
                  81: "香港",
                  82: "澳门",
                  99: "其他"
              },

              /* 每位加权因子 */
              powers: ["7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"],

              /* 第18位校检码 */
              parityBit: ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"],

              /* 性别 */
              genders: {
                  male: "男",
                  female: "女"
              },

              /* 校验地址码 */
              checkAddressCode: function (addressCode) {
                  var check = /^[1-9]\d{5}$/.test(addressCode);
                  if (!check)
                      return false;
                  if (idCardNoUtil.provinceAndCitys[parseInt(addressCode.substring(0, 2))]) {
                      return true;
                  } else {
                      return false;
                  }
              },

              /* 校验日期码 */
              checkBirthDayCode: function (birDayCode) {
                  var check = /^[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))$/.test(birDayCode);
                  if (!check)
                      return false;
                  var yyyy = parseInt(birDayCode.substring(0, 4), 10);
                  var mm = parseInt(birDayCode.substring(4, 6), 10);
                  var dd = parseInt(birDayCode.substring(6), 10);
                  var xdata = new Date(yyyy, mm - 1, dd);
                  if (xdata > new Date()) {
                      return false;// 生日不能大于当前日期
                  } else if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd)) {
                      return true;
                  } else {
                      return false;
                  }
              },

              /* 计算校检码 */
              getParityBit: function (idCardNo) {
                  var id17 = idCardNo.substring(0, 17);
                  /* 加权 */
                  var power = 0;
                  for (var i = 0; i < 17; i++) {
                      power += parseInt(id17.charAt(i), 10) * parseInt(idCardNoUtil.powers[i]);
                  }
                  /* 取模 */
                  var mod = power % 11;
                  return idCardNoUtil.parityBit[mod];
              },

              /* 验证校检码 */
              checkParityBit: function (idCardNo) {
                  var parityBit = idCardNo.charAt(17).toUpperCase();
                  if (idCardNoUtil.getParityBit(idCardNo) == parityBit) {
                      return true;
                  } else {
                      return false;
                  }
              },

              /* 校验15位或18位的身份证号码 */
              checkIdCardNo: function (idCardNo) {
                  // 99开头的不校验
                  if (idCardNo.indexOf("99") === 0) {
                      return true;
                  }
                  // 15位和18位身份证号码的基本校验
                  var check = /^\d{15}|(\d{17}(\d|x|X))$/.test(idCardNo);
                  if (!check)
                      return false;
                  // 判断长度为15位或18位
                  if (idCardNo.length == 15) {
                      return idCardNoUtil.check15IdCardNo(idCardNo);
                  } else if (idCardNo.length == 18) {
                      return idCardNoUtil.check18IdCardNo(idCardNo);
                  } else {
                      return false;
                  }
              },

              // 校验15位的身份证号码
              check15IdCardNo: function (idCardNo) {
                  // 15位身份证号码的基本校验
                  var check = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/.test(idCardNo);
                  if (!check)
                      return false;
                  // 校验地址码
                  var addressCode = idCardNo.substring(0, 6);
                  check = idCardNoUtil.checkAddressCode(addressCode);
                  if (!check)
                      return false;
                  var birDayCode = '19' + idCardNo.substring(6, 12);
                  // 校验日期码
                  return idCardNoUtil.checkBirthDayCode(birDayCode);
              },

              // 校验18位的身份证号码
              check18IdCardNo: function (idCardNo) {
                  // 18位身份证号码的基本格式校验
                  var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(idCardNo);
                  if (!check)
                      return false;
                  // 校验地址码
                  var addressCode = idCardNo.substring(0, 6);
                  check = idCardNoUtil.checkAddressCode(addressCode);
                  if (!check)
                      return false;
                  // 校验日期码
                  var birDayCode = idCardNo.substring(6, 14);
                  check = idCardNoUtil.checkBirthDayCode(birDayCode);
                  if (!check)
                      return false;
                  // 验证校检码
                  // return idCardNoUtil.checkParityBit(idCardNo);
                  return check;
              },

              formateDateCN: function (day) {
                  if (idCardNoUtil.checkBirthDayCode(day)) {
                      var yyyy = day.substring(0, 4);
                      var mm = day.substring(4, 6);
                      var dd = day.substring(6);
                      // alert(yyyy + '-' + mm +'-' + dd);
                      return yyyy + '-' + mm + '-' + dd;
                  }
                  return "";
              },

              // 获取信息
              getIdCardInfo: function (idCardNo) {
                  var idCardInfo = {
                      gender: "", // 性别
                      birthday: "" // 出生日期(yyyy-mm-dd)
                  };
                  if (idCardNo.length == 15) {
                      var aday = '19' + idCardNo.substring(6, 12);
                      idCardInfo.birthday = idCardNoUtil.formateDateCN(aday);
                      if (parseInt(idCardNo.charAt(14)) % 2 == 0) {
                          idCardInfo.gender = idCardNoUtil.genders.female;
                      } else {
                          idCardInfo.gender = idCardNoUtil.genders.male;
                      }
                  } else if (idCardNo.length == 18) {
                      var aday = idCardNo.substring(6, 14);
                      idCardInfo.birthday = idCardNoUtil.formateDateCN(aday);
                      if (parseInt(idCardNo.charAt(16)) % 2 == 0) {
                          idCardInfo.gender = idCardNoUtil.genders.female;
                      } else {
                          idCardInfo.gender = idCardNoUtil.genders.male;
                      }

                  }
                  return idCardInfo;
              },

              // 18位转15位
              getId15: function (idCardNo) {
                  if (idCardNo.length == 15) {
                      return idCardNo;
                  } else if (idCardNo.length == 18) {
                      return idCardNo.substring(0, 6) + idCardNo.substring(8, 17);
                  } else {
                      return null;
                  }
              },

              // 15位转18位
              getId18: function (idCardNo) {
                  if (idCardNo.length == 15) {
                      var id17 = idCardNo.substring(0, 6) + '19' + idCardNo.substring(6);
                      var parityBit = idCardNoUtil.getParityBit(id17);
                      return id17 + parityBit;
                  } else if (idCardNo.length == 18) {
                      return idCardNo;
                  } else {
                      return null;
                  }
              }
          };

          /**
           * 身份证号码验证
           * 目前去掉了尾数码校验，如果需要启用可在本文件搜索idCardNoUtil.checkParityBit(idCardNo);
           * 取消注释即可
           */
          jQuery.validator.addMethod("idCardNo", function (value, element, param) {
              return this.optional(element) || idCardNoUtil.checkIdCardNo(value);
          }, "请输入有效的身份证件号");

          // 联系电话(手机/电话皆可)验证
          jQuery.validator.addMethod("phone", function (value, element) {
              var phone = /^\d|-$/;
              return this.optional(element) || (phone.test(value));
          }, "请输入有效的电话号码：数字或'-'");

          // 手机验证
          jQuery.validator.addMethod("mobile", function (value, element) {
            var phone = /^1\d{10}$/;
            return this.optional(element) || (phone.test(value));
        }, "请输入有效的手机号码");

          //手机号格式验证
          jQuery.validator.addMethod("mobilerule", function(value, element) {
            var length = value.length;
            return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(15[0-9]{1}))+d{8})$/.test(value));
        }, "请输入正确手机号码");
        //银行号长度
        jQuery.validator.addMethod("banklen", function(value, element) {
            var length = value.length;
            return this.optional(element) || (/^[0-9]{12}$/.test(value));
        }, "仅支持输入12位数字");
          //联系人电话
          jQuery.validator.addMethod("contactNumber", function (value, element) {
              var chkPhone = /^1\d{10}$/;
              var fixedTelephone = /^([0][0-9]*)$/;
              var flag = false;
              if((chkPhone.test(value))||(fixedTelephone.test(value))){
                flag = true;
              }
              return (this.optional(element) || (flag));
          }, "请输入有效的手机号码或固定号码");
          
          //座机号码
          jQuery.validator.addMethod("fixedTelephone", function (value, element) {
              var fixedTelephone = /^([0][0-9]*)$/;
              return this.optional(element) || (fixedTelephone.test(value));
          }, "必须以0开头,全部都是数字,不能有-");
          
          // 邮政编码验证
          jQuery.validator.addMethod("zipCode", function (value, element) {
              var tel = /^[0-9]{6}$/;
              return this.optional(element) || (tel.test(value));
          }, "请输入正确的邮政编码");
        
        // 企业名称验证
        jQuery.validator.addMethod("enterpriseName", function (value, element) {
            var tel = /^[\w\u4E00-\u9FA5（）()-·、.]{2,50}$/
            return this.optional(element) || (tel.test(value));
        }, "请输入正确企业名称");

          // 如果带小数，则必须以.5或.0结尾
          jQuery.validator.addMethod("numberEndWithPointFive", function (value, element) {
              var reg = /^(0|[1-9]\d*)([.][05])?$/;
              return this.optional(element) || (reg.test(value));
          }, "必须以.0或.5作为小数结尾");

          $.validator.addMethod("checkNo", function (value, element) {
              var tel = /^(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
              return this.optional(element) || (tel.test(value));
          }, "需为由字母、数字组成, 非数字开头的字符串");
          
          $.validator.addMethod("checkNoNew", function (value, element) {
              var tel = /^[0-9A-Za-z]{7,10}$/;
              return this.optional(element) || (tel.test(value));
          }, "需为由7到10位字母数字组合");
          
          //扩展标准的equalTo校验，基于元素name属性匹配进行equalTo校验
          jQuery.validator.addMethod("equalToByName", function (value, element, param) {
              var target = $(element).closest("form").find("input[name='" + param + "']");
              if (this.settings.onfocusout) {
                  target.unbind(".validate-equalTo").bind("blur.validate-equalTo", function () {
                      $(element).valid();
                  });
              }
              return value === target.val();
          }, "请输入前后相等数据");

          jQuery.validator.addMethod("idCardNoSex", function (value, element, param) {
              var target = $(element).closest("form").find("input[name='" + param + "']:checked");
              var seven = value.substring(16, 17);
              return this.optional(element) || (seven % 2 === target.val() % 2);
          }, "身份证号与性别不匹配");

          //data-rule-requiredByName=“abc”，如果abc元素值不为空，则当前元素也不能为空
          jQuery.validator.addMethod("requiredByName", function (value, element, param) {
              var target = $(element).closest("form").find("input[name='" + param + "']");
              if (target.val().length > 0) {
                  if (value == undefined || value.length == 0) {
                      return false;
                  }
              }
              return true;
          }, "此数据由于依赖关系必须填写");

          //data-rule-remoteCallback=“/remote/validate/url”，如果abc元素值不为空，则当前元素也不能为空
          //data-remoteCallback="alert('validate failure callback')"
          jQuery.validator.addMethod("remoteCallback", function (value, element, param) {
              if (this.optional(element)) {
                  return "dependency-mismatch";
              }

              var previous = this.previousValue(element);
              if (!this.settings.messages[element.name]) {
                  this.settings.messages[element.name] = {};
              }
              previous.originalMessage = this.settings.messages[element.name].remote;
              this.settings.messages[element.name].remote = previous.message;

              param = typeof param === "string" && {
                      url: param
                  } || param;

              if (previous.old === value) {
                  return previous.valid;
              }

              previous.old = value;
              var validator = this;
              this.startRequest(element);
              var data = {};
              data[element.name] = value;
              $.ajax($.extend(true, {
                  url: param,
                  mode: "abort",
                  port: "validate" + element.name,
                  dataType: "json",
                  data: data,
                  success: function (response) {
                      validator.settings.messages[element.name].remote = previous.originalMessage;
                      var valid = response === true || response === "true";
                      if (valid) {
                          var submitted = validator.formSubmitted;
                          validator.prepareElement(element);
                          validator.formSubmitted = submitted;
                          validator.successList.push(element);
                          delete validator.invalid[element.name];
                          validator.showErrors();
                      } else {
                          var showError = true;
                          var callback = $(element).attr("data-remoteCallback");
                          if (callback) {
                              var result = eval(callback);
                              if (result != undefined && result === false) {
                                  showError = false
                              }
                          }
                          if (showError) {
                              var errors = {};
                              var message = response || validator.defaultMessage(element, "remoteCallback");
                              errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
                              validator.invalid[element.name] = true;
                              validator.showErrors(errors);
                          }
                      }
                      previous.valid = valid;
                      validator.stopRequest(element, valid);
                  }
              }, param));
              return "pending";
          }, "数据校验未过");

          //自定义正则表达式校验
          $.validator.addMethod("regex", function (value, element, regexp) {
              var re = new RegExp(regexp);
              return this.optional(element) || re.test(value);
          }, "数据校验未通过");

          $.validator.addMethod("custom", function (value, element, param) {
              var custom = $(element).attr("data-rule-custom");
              if (custom == 'true') {
                  $(element).attr("data-rule-custom", "false");
                  return false;
              } else {
                  return true;
              }
          }, "自定义校验未通过");

          $.validator.addMethod("email", function (value, element, param) {
            var email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

              return this.optional(element) || (email.test(value));
          }, "邮箱不合法");

          jQuery.validator.addMethod("checkFloatPercent", function (value, element) {
              var reg = /(^0(\.(\d?[1-9]))$)|(^([1-9]|([1-9]\d))(\.(\d?[1-9]))?$)|(^100(\.0?0)?$)/;
              return this.optional(element) || (reg.test(value));
          }, "请输入合法百分数(允许两位小数)");

          jQuery.validator.addMethod("checkNum", function (value, element) {
              var reg = /^([1-9][0-9]*)$/;
              return this.optional(element) || (reg.test(value));
          }, "请输入一个大于0的正整数");
          jQuery.validator.addMethod("checkNums", function (value, element) {
            var reg = /^([0-9][0-9]*)$/;
            var money=value.replace(/,/g,"");
            return this.optional(element) || (reg.test(money));
          },"请输入一个大于等于0的正整数");
          jQuery.validator.addMethod("maxNum", function (value, element) {
            var money=value.replace(/,/g, "");
            var flag=true;
            if(money.length>0 && money.length<21){
                flag=true;
            }else{
                flag=false;
            }
            return flag;
          },"注册资本金额至多不超过20位");
          //数量
          jQuery.validator.addMethod("checkCount", function (value, element) {
              var reg = /^[0-9]\d{0,16}(\.\d{1,3})?$/;
              return this.optional(element) || (reg.test(value));
          }, "请输入正确的数字，只能有3位小数");
          //金额
          jQuery.validator.addMethod("checkMoney", function (value, element) {
              if(value!=null&&value==0){
                return false;
              }
              
              if(value!=null&&value.indexOf("00")==0){
                return false;
              }
            
            var reg = /^[0-9]\d{0,16}(\.\d{1,2})?$|^(0\.\d{1,2})?$/;
              return this.optional(element) || (reg.test(value));
          }, "请输入大于0且最多两位小数的合法金额");

          jQuery.validator.addMethod("checkMoneys", function (value, element) {
            // if(value!=null&&value==0){
            //   return false;
            // }
            
            // if(value!=null&&value.indexOf("00")==0){
            //   return false;
            // }
          
          var reg = /^[0-9]\d{0,16}(\.\d{1,2})?$|^(0\.\d{1,2})?$/;
          var money=value.replace(/,/g,"");
            return this.optional(element) || (reg.test(money));
        }, "请输入大于等于0且最多两位小数的合法金额");
          
          //金额允许为零
          jQuery.validator.addMethod("checkMoneyAllowEqual0", function (value, element) {
              if(value!=null&&value.indexOf("00")==0){
                return false;
              }
            var reg = /^[0-9]\d{0,16}(\.\d{1,2})?$|^(0\.\d{1,2})?$/;
              return this.optional(element) || (reg.test(value));
          }, "请输入大于等于0且最多两位小数的合法金额");
          
          

          // 邮政编码验证
          // $.validator.addMethod("checkZipCode", function(value, element) {
          //     var tel = /^[0-9]{6}$/;
          //     return this.optional(element) || (tel.test(value));
          // }, "请正确填写您的邮政编码");

          // 手机号验证
          $.validator.addMethod("checkPhone", function (value, element) {
              var tel = /^1\d{10}$/;
              return this.optional(element) || (tel.test(value));
          }, "请输入正确的手机号");

          $.validator.addMethod("checkUser", function (value, element) {
              var tel = /^(?!\d+$)[\da-zA-Z]+$/;
              return this.optional(element) || (tel.test(value));
          }, "登录账号只能输入3-15位英文字母、数字(不能是纯数字)。");

          $.validator.addMethod("socialCredit", function (value, element) {
            var tel = /^[0-9A-Z]+$/;
            var length = value.length;
            return this.optional(element) || (length== 18 &&tel.test(value));
        }, "请输入正确的统一社会信用代码");

          $.validator.addMethod("checkNo", function (value, element) {
              var tel = /^(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
              return this.optional(element) || (tel.test(value));
          }, "请输入由字母、数字组成, 非数字开头的字符串");

          $.validator.addMethod("checkUserName", function (value, element) {
              var tel = /^(?![a-zA-Z]+$)[0-9A-Za-z_]{6,20}$/;
              return this.optional(element) || (tel.test(value));
          }, "请输入由字母、数字、下划线组成，非数字开头的6-20位字符串");

          $.validator.addMethod("checkPwd", function (value, element) {
              var tel = /(?=.*[a-z])(?=.*\d)(?=.*[#@!~%^&*])[a-z\d#@!~%^&*]{6,16}/;
              return this.optional(element) || (tel.test(value));
          }, "密码6-10位，仅支持字母、数字和常用字符");

          $.validator.addMethod("checkLoginName", function (value, element) {
              var tel = /^(?![0-9]+$)?(?![a-zA-Z]+$)?[0-9A-Za-z]{1,30}$/;
              return this.optional(element) || (tel.test(value));
          }, "仅支持由字母或数字");

          $.validator.addMethod("checkEnterpriseName", function (value, element) {
              var tel = /^[0-9A-Za-z\u4e00-\u9fa5]*(\([0-9A-Za-z\u4e00-\u9fa5]+\)|\（[0-9A-Za-z\u4e00-\u9fa5]+\）)?([0-9A-Za-z\u4e00-\u9fa5]*$)+$/;
              return this.optional(element) || (tel.test(value));
          }, "请输入合理的名称");
          
          $.validator.addMethod("checkEnterpriseNameNew", function (value, element) {
            var reg = /[^\a-\z\A-\Z\u4E00-\u9FA5\(\（\）\)]/g;
              return this.optional(element) || !(reg.test(value));
          }, "请输入合理的名称");
          
          $.validator.addMethod("normalStr", function (value, element) {
              var tel = /^[0-9A-Za-z\u4e00-\u9fa5]*$/;
              return this.optional(element) || (tel.test(value));
          }, "仅支持汉字、字母或数字");

          $.validator.addMethod("letterOrNumber", function (value, element) {
              var tel = /^[0-9A-Za-z]*$/;
              return this.optional(element) || (tel.test(value));
          }, "仅支持字母或数字");

          jQuery.validator.addMethod("gtZero", function (value, element) {
              var result = false;
              
              if(value!=null&&value.indexOf("00")==0){
                return this.optional(element) || result;
              }
              
              var reg = /^[0-9]\d{0,17}(\.\d{1,2})?$/;
              if (reg.test(value) && Number(value) > 0) {
                  result = true
              }
              return this.optional(element) || result;
          }, "请输入大于0且最多两位小数的合法金额");
          //修改合同编号校验 STA 20190515
          jQuery.validator.addMethod("tradingCode", function (value, element) {
              var reg = /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\(\（\）\)\-]/g;
            var flag = reg.test(value);
              return this.optional(element) || !flag;
          }, "只能输入汉字，字母，数字，括号和-");
        //修改合同编号校验 END 20190515
          jQuery.validator.addMethod("tradingName", function (value, element) {
            var reg = /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\(\（\）\)\-]/g;
            var flag = reg.test(value);
              return this.optional(element) || !flag;
          }, "只能输入汉字，字母，数字，括号和-");
          
          
          jQuery.validator.addMethod("facAllName", function (value, element) {
            var reg = /[^\a-\z\A-\Z\u4E00-\u9FA5\(\（\）\)]/g;
            var flag = reg.test(value);
              return this.optional(element) || !flag;
          }, "仅支持中英文和括号");
          //范围金额
          jQuery.validator.addMethod("rangeMoney", function (value, element) {
              var reg = /^[0-9]\d{0,17}(\.\d{1,2})?(\~([0-9]\d{0,17}(\.\d{1,2})?)?)?$/;
              return this.optional(element) || (reg.test(value));
          }, "请输入正确格式的金额，如（0~100）");
          
          // 自定义验证联系电话（可以输入手机号，电话号 -）
          jQuery.validator.addMethod("checkMobileAndPhone", function (value, element) {
              var phone = /^[\d-]*$/;
              return this.optional(element) || (phone.test(value));
          }, "请输入有效的电话号码：数字或'-'");

          // 20171218自定义验证联系电话（请输入有效的电话号码:区号后面不能带有'-'）
          jQuery.validator.addMethod("checkfixedPhone", function (value, element) {
              var phone =/^([0-9]{3,4})?[0-9]{7,8}$/;
              return this.optional(element) || (phone.test(value));
          }, "请输入有效的电话号码:区号后面不能带有'-'");

          $.validator.addMethod("checkCommonStr", function (value, element) {
              // var tel = /^[0-9A-Za-z#\(\)\u4e00-\u9fa5]*$/;
              var tel = /^[0-9A-Za-z#\u4e00-\u9fa5]*(\([0-9A-Za-z#\u4e00-\u9fa5]+\)|\（[0-9A-Za-z#\u4e00-\u9fa5]+\）)?[0-9A-Za-z#\u4e00-\u9fa5]*$/;
              return this.optional(element) || (tel.test(value));
          }, "仅支持汉字、字母、数字、括号和#号");

          $.validator.addMethod("keyboardStr", function (value, element) {
              var tel = /^([A-Z]|[a-z]|[0-9]|((?=[\x21-\x7e]+)[^A-Za-z0-9])){6,20}/;
              return this.optional(element) || (tel.test(value));
          }, "仅支持字母、数字和常用字符");
          
          jQuery.validator.addMethod("gtZeroReg", function (value, element) {
              var result = false;
              
              if(value!=null&&value.indexOf("00")==0){
                return this.optional(element) || result;
              }
              
              var reg = /^[0-9]\d{0,8}(\.\d{1,6})?$/;
              if (reg.test(value) && Number(value) >= 0) {
                  result = true
              }
              return this.optional(element) || result;
          }, "输入金额大于等于0且整数最多为9位、小数最多为6位");
          
          $.validator.addMethod("compareNames", function (value, element) {
             var target = $(element).closest("form").find("input[name='enterpriseNm']");
            var enterName = target.val();
            var accountName = value;
              var flag = true;
            if(enterName != accountName){
                flag = false;
              }
              return flag;
          }, "您输入的银行户名与企业全称不符");
          
          /**
           * 校验字符串长度
           */
          jQuery.validator.addMethod("checkLength", function (value, element) {
              if (value == "") {
                  return this.optional(element);
              }
              var regex = /^(.{10}|.{12})$/;
              if (!regex.test(value)) {
                  return false;
              }
              return true;
          }, "只能输入10位或者12位");
          
          // 联行号验证   
          jQuery.validator.addMethod("checkBankCode", function(value, element) {   
              var tel = /^[0-9]{12}$/;
              return this.optional(element) || (tel.test(value));
          }, "请填写12位联行号号码");
          // 密码校验   
          jQuery.validator.addMethod("passwordNew", function(value, element) {   
                var tel = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/;
                return this.optional(element) || (tel.test(value));
            }, "密码必须是8-16位，需同时包含大写字母、小写字母、数字、特殊字符4种");
            jQuery.validator.addMethod("passwordNewLx", function(value, element) {   
                var tel = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[A-Z])(?=.*\d)(?=.*[!.@#$%^&*()\-+])(?!.*(.)\1{2})(?!.*(?:012|123|234|345|456|567|678|789))[a-zA-Z0-9!.@#$%^&*()\-+]{8,}$/;
                return this.optional(element) || (tel.test(value));
            }, "密码中不能包含3个及以上连续的数字或连续相同的字符");
          /**
           * 校验相似度
           */
          jQuery.validator.addMethod("similar", function (value, element, param) {
            var account = $(param).val()
            function similar(s, t, f) {
                if (!s || !t) {
                  return 0
                }
                if(s === t){
                  return 100;
                }
                var l = s.length > t.length ? s.length : t.length
                var n = s.length
                var m = t.length
                var d = []
                f = f || 2
                var min = function (a, b, c) {
                  return a < b ? (a < c ? a : c) : (b < c ? b : c)
                }
                var i, j, si, tj, cost
                if (n === 0) return m
                if (m === 0) return n
                for (i = 0; i <= n; i++) {
                  d[i] = []
                  d[i][0] = i
                }
                for (j = 0; j <= m; j++) {
                  d[0][j] = j
                }
                for (i = 1; i <= n; i++) {
                  si = s.charAt(i - 1)
                  for (j = 1; j <= m; j++) {
                    tj = t.charAt(j - 1)
                    if (si === tj) {
                      cost = 0
                    } else {
                      cost = 1
                    }
                    d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
                  }
                }
                var res = (1 - d[n][m] / l) *100
                return res.toFixed(f)
              }
              
            return similar(account,value)<80
                
            }, "密码与账号高度相似，请修改");
          //验证金额
          jQuery.validator.addMethod("gtMoneyZero", function (value, element) {
              var result = false;
              if(value!=null&&value.indexOf("00")==0){
                  return this.optional(element) || result;
              }
              if(value.indexOf(",") != -1){
                  value = value.replace(/,/g,'');
              }
              var reg = /^[0-9]\d{0,17}(\.\d{1,2})?$/;
              if (reg.test(value) && Number(value) > 0) {
                  result = true
              }
              return this.optional(element) || result;
          }, "请输入大于0且最多两位小数的合法金额");
      }
     

  };

}();
FormValidation.init();